<template>
  <div class="personalInfo">
    <van-nav-bar
        left-arrow
        @click-left="handleClickLeft"
        :title="$t('基本信息')"
    >
      <template #left>
        <van-icon name="arrow-left" class="nav_left_icon" size="18px"/>
      </template>
    </van-nav-bar>
    <!--     身份信息-->
    <div class="wrapper">
      <div class="cell_content_list">
        <div class="personalInfo_box_card">
          <div class="personalInfo_box_card_header">
            <span class="text_highlight">{{ $t('基本信息') }}</span>
          </div>
          <!--        电子邮件-->
          <div class="cell_content_item" style="display: block">
            <div>
              <input class="input" v-model="mail"
                     @focus="showEmailList = true"
                     @blur="showEmailList = false,inputEventPoint('ljxcc6')"
                     @update:model-value="changeEmailValue" style="width: 100%;"
                     :placeholder="$t('请输入电子邮箱')"/>
            </div>
            <van-popover v-model:show="showEmailList" :actions="emailList"
                         @select="onChangeEmailValue" placement="bottom-start">
              <template #reference>
                <div style="width: 0"></div>
              </template>
            </van-popover>
          </div>

          <!--        Facebook-->
          <div class="cell_content_item">
            <input class="input"
                   @blur="inputEventPoint('pfc42v')"
                   v-model="facebook"
                   :placeholder="$t('请输入Link_Facebook')"/>
          </div>

          <!--      婚姻状况-->
          <div class="cell_content_item" @click="maritalClick">
            <div style="position: relative">
              <input class="input" @blur="inputEventPoint('j88hrw')" v-model="maritalText" :readonly="true"
                     :placeholder="$t('请选择婚姻状况')"/>
              <img class="input_icon" src="../../assets/my/input_right.png">
            </div>
          </div>
          <!--      学历-->
          <div class="cell_content_item" @click="ducationClick">
            <div style="position: relative">
              <input class="input" @blur="inputEventPoint('4vq2oy')" v-model="ducationText" :readonly="true"
                     :placeholder="$t('请选择学历')"/>
              <img class="input_icon" src="../../assets/my/input_right.png">
            </div>
          </div>
          <!--      行业类型-->
          <div class="cell_content_item" @click="industryTypeClick">
            <div style="position: relative">
              <input class="input"
                     @blur="inputEventPoint('lnexr7')"
                     v-model="industryTypeText" :readonly="true"
                     :placeholder="$t('请选择行业类型')"/>
              <img class="input_icon" src="../../assets/my/input_right.png">
            </div>
          </div>
          <!--     发薪日-->
          <div class="cell_content_item" @click=" salaryDateShow = true">
            <div style="position: relative">
              <input class="input" @blur="inputEventPoint('u5p321')" v-model="payday" :readonly="true"
                     :placeholder=" $t('请选择发薪日')"/>
              <img class="input_icon" src="../../assets/my/input_right.png">
            </div>
          </div>
          <!--      每月净收入-->
          <div class="cell_content_item">
            <input class="input"
                   @blur="inputEventPoint('dri3t0')"
                   v-model="monthlyIncome" type="tel"
                   :placeholder="$t('每月净收入')"/>
          </div>
        </div>

        <div class="personalInfo_box_card">
          <div class="personalInfo_box_card_header">
            <div style=""><span
                class="text_highlight">{{ $t('联系信息') }}</span></div>
          </div>
          <!--     联系人1-->
          <div class="cell_content_item" style="display:flex;align-items: center;"
               @click="relationShow = true">
            <div class="flex_center input_contacts">
              <div style="position: relative;width: 30%;margin-right: 10px">
                <input class="input " v-model="contactscolFourRelation_text" :readonly="true"
                       placeholder="Relation" style="border: 0"/>
                <img class="input_icon" style="width: 15px;height: 12px;right: 5px" src="../../assets/select_right.png">
              </div>
              <div style="position: relative;flex: 1">
                <input class="input" v-model="mobile"
                       :readonly="true"
                       style="border: 0"
                       placeholder="Contact 1"/>
                <div v-show="contactsInfo.name" class="contactsInfo_name">
                  {{ contactsInfo.name }}
                </div>
                <img class="contacts_icon input_icon" src="../../assets/my/contacts_icon.png">
              </div>
            </div>
          </div>
          <!--     联系人2-->
          <div class="cell_content_item" style="display:flex;align-items: center;"
               @click="relationsSpareShow = true">
            <div class="flex_center input_contacts">
              <div style="position: relative;width: 30%;margin-right: 10px">
                <input class="input " v-model="relation_spare_text" :readonly="true"
                       placeholder="Relation" style="border: 0"/>
                <img class="input_icon" style="width: 15px;height: 12px;right: 5px" src="../../assets/select_right.png">
              </div>
              <div style="position: relative;flex: 1">
                <input class="input" v-model="mobile_spare"
                       :readonly="true"
                       style="border: 0"
                       placeholder="Contact 2"/>
                <div v-show="contactsInfo.name_spare" class="contactsInfo_name">
                  {{ contactsInfo.name_spare }}
                </div>
                <img class="contacts_icon input_icon" src="../../assets/my/contacts_icon.png">
              </div>
            </div>
          </div>
          <!--     联系人3-->
          <div class="cell_content_item" style="display:flex;align-items: center;"
               @click="relationsTwoShow = true">
            <div class="flex_center input_contacts">
              <div style="position: relative;width: 30%;margin-right: 10px">
                <input class="input"
                       v-model="relationsTwoText" :readonly="true"
                       placeholder="Relation"
                       style="border: 0"
                />
                <img class="input_icon" style="width: 15px;height: 12px;right: 5px" src="../../assets/select_right.png">
              </div>
              <div style="position: relative;flex: 1">
                <input class="input " v-model="contactscolThreePhone"
                       :readonly="true"
                       style="border: 0"
                       placeholder="Contact 3"/>
                <div v-show="contactsInfo.contactscolThreeName"
                     class="contactsInfo_name">{{ contactsInfo.contactscolThreeName }}
                </div>
                <img class="contacts_icon input_icon" src="../../assets/my/contacts_icon.png">
              </div>
            </div>
          </div>
          <!--     联系人4-->
          <div class="cell_content_item"
               style="display:flex;align-items: center;"
               @click="relationsThreeShow = true">
            <div class="flex_center input_contacts">
              <div style="position: relative;width: 30%;margin-right: 10px">
                <input class="input"
                       v-model="relationsThreeText" :readonly="true"
                       placeholder="Relation" style="border: 0"/>
                <img class="input_icon" style="width: 15px;height: 12px;right: 5px" src="../../assets/select_right.png">
              </div>
              <div style="position: relative;flex: 1;">
                <input class="input "
                       style="border: 0"
                       v-model="contactscolFourPhone"
                       :readonly="true"
                       placeholder="Contact 4"/>
                <div v-show="contactsInfo.contactscolFourName"
                     class="contactsInfo_name">
                  {{ contactsInfo.contactscolFourName }}
                </div>
                <img class="contacts_icon input_icon" src="../../assets/my/contacts_icon.png">
              </div>
            </div>
          </div>
        </div>
        <!--        证件信息-->
        <div class="personalInfo_box_card">
          <div class="personalInfo_box_card_header">
            <div style=""><span
                class="text_highlight">Identity information</span></div>
          </div>
          <!--      选择身份证类型-->
          <div class="cell_content_item" @click="idCardTypeShow = true"
          >
            <div style="position: relative">
              <input class="input" v-model="typeOfCertificate"
                     @blur="inputEventPoint('4jk4wk')"
                     :readonly="true"
                     :placeholder="$t('身份证类型')"/>
              <img class="input_icon" src="../../assets/my/input_right.png">
            </div>
          </div>
          <!--        上传身份证正面-->
          <div class="cell_content_item">
            <div :class="{'grid_layout':switchConfig.isLivingSwitch}">
              <div class="card_box" @click="idCardPositiveShow">
                <div>
                  <img class="idCard_img" v-if="positive" :src="positive">
                  <div v-else style="position: relative;">
                    <img class="idCard_img" src="../../assets/identity/card_img_front.png">
                    <div class="text">
                      Front of your ID
                    </div>
                  </div>
                </div>
              </div>
              <!--              活体-->
              <div v-if="switchConfig.isLivingSwitch" class="card_box" @click="livingBodyDetection">
                <img class="idCard_img" v-if="livingImageUrl" :src="livingImageUrl">
                <div v-else style="position: relative;">
                  <img class="idCard_img" src="../../assets/identity/card_img_face.png">
                  <div class="text">Live detection</div>
                </div>
              </div>
            </div>
          </div>
          <!--      身份证号码-->
          <div class="cell_content_item">
            <input class="input" :readonly="isOcrIdentify"
                   v-model="idCard"
                   :placeholder="$t('身份证号码')"/>
          </div>
          <!--        父姓-->
          <div class="cell_content_item " style="display: block">
            <input class="input" v-model="fatherSurname" :readonly="isOcrIdentify"
                   placeholder="First name"/>
          </div>
          <!--        母姓-->
          <div class="cell_content_item " style="display: block">
            <input class="input" v-model="motherSurname" :readonly="isOcrIdentify"
                   placeholder="Middlet name"/>
          </div>
          <!--        姓名-->
          <div class="cell_content_item " style="display: block">
            <input class="input" v-model="secondName" :readonly="isOcrIdentify"
                   placeholder="last name"/>
          </div>
          <!--      选择性别-->
          <div class="cell_content_item" @click="selectSex">
            <div style="position: relative">
              <input class="input" v-model="gender" :readonly="true"
                     :placeholder="$t('性别')"/>
              <img class="input_icon" src="../../assets/my/input_right.png">
            </div>
          </div>
          <!--      选择生日-->
          <div class="cell_content_item" @click="selectBirth">
            <div style="position: relative">
              <input class="input" :value="dateBirth? $dateFormat(new Date(dateBirth), 'dd/mm/YYYY') : null"
                     :readonly="true"
                     :placeholder="$t('生日')"/>
              <img class="input_icon" src="../../assets/my/input_right.png">
            </div>
          </div>

        </div>
        <div style="text-align: center;padding-bottom: 20px">
          <van-button round class="next_confirm" type="primary" @click="confirm">{{ $t('下一步') }}</van-button>
        </div>
        <van-action-sheet
            v-model:show="idCardTypeShow"
            @select="idCardTypeConfirm"
            :description="$t('身份证类型')"
            :cancel-text="$t('取消')"
            close-on-click-action
        >
          <div style="background-color: #FFFFFF;padding: 15px;">
            <van-button v-for="item in idCardTypeColumns" round block :key="item.key" @click="idCardTypeConfirm(item)"
                        style="margin-bottom: 20px;background-color: #F1F2F5;font-size: 18px">{{ item.value }}
            </van-button>
          </div>
        </van-action-sheet>
        <!--        婚姻状况选择-->
        <van-action-sheet v-model:show="maritalShow">
          <van-picker @confirm="maritalConfirm" @cancel="maritalShow = false"
                      :columns-field-names="{  text: 'value'}"
                      :columns="maritalColumns"/>
        </van-action-sheet>
        <!--        学历选择面板-->
        <van-action-sheet v-model:show="ducationShow">
          <van-picker @confirm="ducationConfirm" @cancel="ducationShow = false"
                      :columns-field-names="{  text: 'value'}"
                      :columns="ducationColumns"/>
        </van-action-sheet>
        <!--        行业类型选择面板-->
        <van-action-sheet v-model:show="industryTypeShow">
          <van-picker @confirm="industryTypeConfirm" @cancel="industryTypeShow = false"
                      :columns-field-names="{  text: 'value'}"
                      :columns="industryTypeColumns"/>
        </van-action-sheet>
        <!--      选择发薪日-->
        <van-action-sheet v-model:show="salaryDateShow">
          <van-picker @confirm="salaryDateConfirm" @cancel="salaryDateShow = false"
                      :columns-field-names="{  text: 'value'}"
                      :columns="salaryDateColumns"/>
        </van-action-sheet>
        <!--       选择性别-->
        <van-action-sheet v-model:show="sexShow" :actions="sexActions" @select="onSexSelect"/>

        <!--      选择生日-->
        <van-action-sheet v-model:show="birthdayShow">
          <van-datetime-picker
              @confirm="onBirthdaySelect"
              @cancel="birthdayShow = false"
              v-model="currentDate"
              :columns-order="['day', 'month', 'year']"
              type="date"
              :min-date="minDate"
              :max-date="maxDate"
          />
        </van-action-sheet>
        <!--    联系人关系1-->
        <van-action-sheet v-model:show="relationShow">
          <van-picker @confirm="relationConfirm" @cancel="relationShow = false"
                      :columns-field-names="{  text: 'value'}"
                      :columns="selectDataOne"/>
        </van-action-sheet>
        <!-- 联系人关系2-->
        <van-action-sheet v-model:show="relationsSpareShow">
          <van-picker @confirm="relationsSpareConfirm" @cancel="relationsSpareShow = false"
                      :columns-field-names="{  text: 'value'}"
                      :columns="selectDataTwo"/>
        </van-action-sheet>
        <!-- 联系人关系3-->
        <van-action-sheet v-model:show="relationsTwoShow">
          <van-picker @confirm="relationsTwoConfirm" @cancel="relationsTwoShow = false"
                      :columns-field-names="{  text: 'value'}"
                      :columns="selectDataThree"/>
        </van-action-sheet>
        <!-- 联系人关系4-->
        <van-action-sheet v-model:show="relationsThreeShow">
          <van-picker @confirm="relationsThreeConfirm" @cancel="relationsThreeShow = false"
                      :columns-field-names="{  text: 'value'}"
                      :columns="selectDataFour"/>
        </van-action-sheet>
        <van-popup v-model:show="idCardTypeConfirmShow" closeable>
          <div
              style="padding: 20px 10px;box-sizing: border-box;background-color: #FFFFFF;border-radius: 8px;width: 80vw">
            <img style="width: 100%;height: 100%;padding-top: 20px"
                 v-if="typeOfCertificate && idCardTypeImagePerView"
                 :src="idCardTypeImagePerView"/>
            <div style="margin-top: 15px;text-align: center">
              <van-uploader accept=".jpg,.jpeg,.png,.JPG,.JPEG" capture="camera"
                            :before-read="beforeRead"
                            :after-read="updatePositive">
                <van-button class="next_confirm" style="padding: 0 40px;width: 100%" round type="primary">Camera
                </van-button>
              </van-uploader>
            </div>
          </div>
        </van-popup>
        <van-popup v-model:show="dialogRetentionShow" round>
          <template #default>
            <div class="dialog_body">
              <div class="content_text">{{ $t('申请马上成功') }}
                <p class="active">{{ $t('只需两步即可立即获得资金') }}</p>
                {{ $t('你真的想退出吗?') }}
              </div>
              <div style="margin-top: 20px;text-align: center">
                <van-button type="primary" round style="width: 80%" class="continue_apply"
                            @click="dialogRetentionShow = false">{{
                    $t('继续申请')
                  }}
                </van-button>
                <van-button class="reject_btn" round @click="$router.replace('/hScmlvxSUkDQ/UjRzDSClllpS')">
                  {{ $t('残忍拒绝') }}
                </van-button>
              </div>
            </div>
          </template>
        </van-popup>
      </div>
    </div>
  </div>
</template>

<script>
import {ref, toRefs, reactive, onMounted, nextTick,} from 'vue'
import {useI18n} from 'vue-i18n'
import {Dialog, Toast} from 'vant'
import {
  personalInfoSelect,
  selectCitys,
  savePersonalInfo,
  uploadOcr,
  uploadUserInfo,
  getConfigSwitch,
  saveWorkInfo, saveContacts, userInfoConfirm
} from '@/api/home'
import {fetchUserInfo, upLoadInputPoint, upLoadPoint} from '@/api/my'
import {
  compressImage,
  dateFormat,
  debounce,
  processNext,
  setResourcesShow,
  upLoadAdjustPoint,
  verifiesPhone
} from '@/utils/tool'
import {useRoute, useRouter} from "vue-router";
import {useStore} from "vuex";

const salaryDateColumns = []
for (let i = 0; i <= 30; i++) {
  salaryDateColumns.push(i + 1)
}

export default {
  setup() {
    const {t} = useI18n()
    const router = useRouter()
    const store = useStore()
    const dialogRetentionShow = ref(false)
    // 所有下拉
    let allSelectData = ref([])
    const salaryDateShow = ref(false)
    const productName = localStorage.getItem('productName')
    const idCardTypeColumns = ref([])
    const idCardTypeShow = ref(false)
    const currentDate = ref(new Date(1990, 0, 1))
    const selectDataOne = ref([])
    const selectDataTwo = ref([])
    const selectDataThree = ref([])
    const selectDataFour = ref([])
    const resourcesShow = ref({})
    const idCardTypeImagePerView = ref('')
    const emailList = ref([])
    const emailStr = [
      'gmail.com',
      'yahoo.com',
      'outlook.com',
      'mail.com',
      'hotmail.com',
      'zoho.com',
      'icloud.com'
    ]
    const showEmailList = ref(false)
    let userContact = reactive({
      mail: '',
      facebook: '',
      zipCode: '',
      payday: null,
      monthlyIncome: null,
      industry: null
    })
    const isOcrIdentify = ref(false)
    const contactsInfo = reactive({
      relation: null,
      name: null,
      mobile: null,
      relation_spare: null,
      name_spare: null,
      mobile_spare: null,
      contactscolFourRelation: null,
      contactscolFourName: null,
      contactscolFourPhone: null,
      contactscolThreePhone: null,
      contactscolThreeRelation: null,
      contactscolThreeName: null,
    })
    const userInfo = reactive({
      typeOfCertificate: null,
      name: null,
      idCard: null,
      gender: null,
      dateBirth: null,
      positive: null,
      fatherSurname: null,
      motherSurname: null,
      secondName: null,
      livingImageUrl: null
    })
    const idCardTypeConfirmShow = ref(false)
    const switchConfig = reactive({
      isLivingSwitch: false,
      isOcrSwitch: false,
      isFaceSwitch: false,
    })
    let sexSheet = reactive({
      sexShow: false,
      sexActions: [{name: t('男'), key: 1}, {name: t('女'), key: 0}],
      onSexSelect: (value) => {
        userInfo.gender = value.name
        sexSheet.sexShow = false
      },
      selectSex: () => {
        if (isOcrIdentify.value) return
        sexSheet.sexShow = true
      }
    })
    // 选择生日
    let birthdaySheet = reactive({
      minDate: new Date(1910, 0, 1),
      maxDate: new Date(),
      endMaxDate: new Date(2090, 0, 1),
      birthdayShow: false,
      onBirthdaySelect: (value) => {
        userInfo.dateBirth = dateFormat(value, 'YYYY/mm/dd')
        birthdaySheet.birthdayShow = false
      },
      selectBirth: () => {
        if (isOcrIdentify.value) return
        birthdaySheet.birthdayShow = true
      }
    })
    // 选择婚姻状况
    let maritalSheet = reactive({
      maritalShow: false,
      maritalText: '',
      maritalKey: null,
      maritalColumns: [],
      maritalConfirm: (value) => {
        maritalSheet.maritalText = value.value
        maritalSheet.maritalKey = value.key
        maritalSheet.maritalShow = false
      },
      maritalClick: () => {
        maritalSheet.maritalShow = true
        maritalSheet.maritalColumns = allSelectData.value.filter(item => item.type === 2)
      }
    })

    // 行业类型
    let industryTypeSheet = reactive({
      industryTypeShow: false,
      industryTypeText: '',
      industryTypeColumns: [],
      industryTypeConfirm: (value) => {
        industryTypeSheet.industryTypeText = value.value
        userContact.industry = value.key
        industryTypeSheet.industryTypeShow = false
      },
      industryTypeClick: () => {
        industryTypeSheet.industryTypeShow = true
        industryTypeSheet.industryTypeColumns = allSelectData.value.filter(item => item.type === 6)
      }
    })
// 联系人1
    let relationSheet = reactive({
      relationShow: false,
      contactscolFourRelation_text: '',
      relationConfirm: ({key, value}) => {
        contactsInfo.contactscolFourRelation = key
        relationSheet.contactscolFourRelation_text = value
        relationSheet.relationShow = false
        openAddressBook(0)
      },
      relationClick: () => {
        relationSheet.relationShow = true
      }
    })
    // 其他联系人2
    let relationsSpareSheet = reactive({
      relationsSpareShow: false,
      relation_spare_text: '',
      relationsSpareConfirm: ({key, value}) => {
        contactsInfo.relation = key
        relationsSpareSheet.relation_spare_text = value
        relationsSpareSheet.relationsSpareShow = false
        openAddressBook(1)
      },
      relationsSpareClick: () => {
        relationsSpareSheet.relationsSpareShow = true
      }
    })
    // 其他联系人3
    let relationsTwoSheet = reactive({
      relationsTwoShow: false,
      relationsTwoText: '',
      relationsTwoConfirm: ({key, value}) => {
        contactsInfo.relation_spare = key
        relationsTwoSheet.relationsTwoText = value
        relationsTwoSheet.relationsTwoShow = false
        openAddressBook(2)
      },
      relationsTwoClick: () => {
        relationsTwoSheet.relationsTwoShow = true
      }
    })
    // 其他联系人4
    let relationsThreeSheet = reactive({
      relationsThreeShow: false,
      relationsThreeText: '',
      relationsThreeConfirm: ({key, value}) => {
        contactsInfo.contactscolThreeRelation = key
        relationsThreeSheet.relationsThreeText = value
        relationsThreeSheet.relationsThreeShow = false
        openAddressBook(3)
      },
      relationsThreeClick: () => {
        relationsThreeSheet.relationsThreeShow = true
      }
    })

// 选择学历信息
    let ducationSheet = reactive({
      ducationShow: false,
      ducationText: '',
      ducationKey: null,
      ducationColumns: [],
      ducationConfirm: (value) => {
        ducationSheet.ducationText = value.value
        ducationSheet.ducationKey = value.key
        ducationSheet.ducationShow = false
      },
      ducationClick: () => {
        ducationSheet.ducationShow = true
        ducationSheet.ducationColumns = allSelectData.value.filter(item => item.type === 3)
      }
    })
    const beforeRead = (file) => {
      if (!userInfo.typeOfCertificate) {
        Toast(t('请选择证件类型'))
        return Promise.reject()
      }
      return new Promise(async (resolve, reject) => {
        const fileType = ['image/jpeg', 'image/png', 'image/jpg']
        if (fileType.indexOf(file.type) === -1) {
          Toast('upload_image');
          reject()
        } else if (file.size < Math.pow((1024 * 1.35), 2)) {
          // 小于2m不压缩
          resolve(file)
        } else {
          // 压缩图片
          const caseFile = await compressImage(file)
          resolve(caseFile)
        }
      })
    }

    // 匹配ocr识别的结果
    function matchCardTypeInfo(data, cardType) {
      let dataObj = {
        idCard: null,
        gender: null,
        dateBirth: null,
        fatherSurname: null,
        motherSurname: null,
        secondName: null,
      }
      switch (cardType) {
        case 'UMID' :
          dataObj.idCard = data.idNumber
          dataObj.gender = data.gender
          dataObj.dateBirth = data.birthdayParsed
          dataObj.fatherSurname = data.givenName
          dataObj.motherSurname = data.middleName
          dataObj.secondName = data.surName
          break;
        case 'SSS' :
          dataObj.idCard = data.idNumber
          dataObj.dateBirth = data.birthdayParsed
          break;
        case 'TIN' :
          dataObj.idCard = data.idNumber
          dataObj.dateBirth = data.birthdayParsed
          break;
        case 'PASSPORT' :
          dataObj.idCard = data.idNumber
          dataObj.gender = data.gender
          dataObj.dateBirth = data.birthdayParsed
          dataObj.fatherSurname = data.givenName
          dataObj.motherSurname = data.middleName
          dataObj.secondName = data.surName
          break;
        case 'DRIVINGLICENSE' :
          dataObj.idCard = data.idNumber
          dataObj.gender = data.gender
          dataObj.dateBirth = data.birthdayParsed
          break;
        case 'NATIONALID' :
          dataObj.idCard = data.idNumber
          dataObj.dateBirth = data.birthdayParsed
          dataObj.fatherSurname = data.firstName
          dataObj.motherSurname = data.middleName
          dataObj.secondName = data.lastName
          break;
        case 'POSTALID' :
          dataObj.idCard = data.idNumber
          dataObj.dateBirth = data.birthdayParsed
          break;
        case 'VOTERID' :
          dataObj.idCard = data.idNumber
          dataObj.dateBirth = data.birthdayParsed
          break;
        case 'HEALTHCARD' :
          dataObj.idCard = data.idNumber
          dataObj.dateBirth = data.birthdayParsed
          dataObj.gender = data.gender
          break;
      }
      return dataObj
    }

    // 上传正面
    const updatePositive = async (file) => {
      Toast.loading({
        message: t('加载中'),
        forbidClick: true,
        duration: 0,
      })
      // 上传接口
      const upload = async () => {
        const res = await upDateLoad(file.file, 2)
        upLoadAdjustPoint({eventName: '4uho5h'})
        userInfo.positive = res
      }
      idCardTypeConfirmShow.value = false
      // ocr 关闭
      if (!switchConfig.isOcrSwitch) {
        await upload()
        Toast.clear()
      } else {
        //该证件是否可以ocr识别
        const formData = new FormData()
        formData.append('file', file.file)
        formData.append('key', idCardTypeColumns.value.find(v => userInfo.typeOfCertificate === v.value).key)
        const res = await uploadOcr(formData)
        if (res.code === 1) {
          const data = JSON.parse(res.data)
          const formatData = matchCardTypeInfo(data.result, data.cardType)
          console.log(formatData)
          userInfo.idCard = formatData.idCard || null
          userInfo.gender = formatData.gender === 'M' ? t('男') : formatData.gender === 'F' ? t('女') : null
          userInfo.dateBirth = formatData.dateBirth ? formatData.dateBirth : null
          userInfo.fatherSurname = formatData.fatherSurname || null
          userInfo.motherSurname = formatData.motherSurname || null
          userInfo.secondName = formatData.secondName || null
          await upload()
          Toast.clear()
        } else {
          upLoadPoint({type: 4})
        }
      }
    }
    const upDateLoad = async (file, type) => {
      const formData = new FormData()
      formData.append('file', file)
      formData.append('type', type)
      const res = await uploadUserInfo(formData)
      if (res.code === 1 && res.data) {
        console.log(res.data)
        return res.data
      }
    }

    //  调用安卓活体检测
    function livingBodyDetection() {
      let timer
      let timerNum
      if (switchConfig.isLivingSwitch) {
        // 调用安卓活体检测页面
        if (window.android) {
          const isLiving = window.android.getLivenessImageUrl()
          if (isLiving) {
            userInfo.livingImageUrl = isLiving
          } else {
            upLoadAdjustPoint({eventName: 'moee30'})
            window.android.startLivenessDetection();
            timer = setInterval(() => {
              // 轮询超时20秒 自动退出
              if (timerNum >= 20) {
                clearInterval(timer)
              }
              if (window.android.getLivenessImageUrl()) {
                upLoadAdjustPoint({eventName: '8pht0m'})
                userInfo.livingImageUrl = window.android.getLivenessImageUrl()
                clearInterval(timer)
              }
              timerNum++
            }, 1000)
          }
        }
      }
    }

    function idCardPositiveShow() {
      if (!userInfo.typeOfCertificate) {
        return Toast(t('请选择证件类型'))
      }
      upLoadAdjustPoint({eventName: 'vcwdov'})
      idCardTypeImagePerView.value = ''
      idCardTypeConfirmShow.value = true
      nextTick(() => {
        idCardTypeImagePerView.value = require(`../../assets/identity/${userInfo.typeOfCertificate}_ID.png`)
      })
    }

    // 选择身份证
    const idCardTypeConfirm = ({value}) => {
      idCardTypeShow.value = false
      userInfo.typeOfCertificate = value
    }
    const salaryDateConfirm = (value) => {
      userContact.payday = value
      salaryDateShow.value = false
    }

    const verificationInfo = () => {
      let message = ''
      const {mail, facebook, industry, payday, monthlyIncome} = userContact
      const {
        idCard,
        gender,
        dateBirth,
        livingImageUrl,
        positive,
        fatherSurname, motherSurname, secondName
      } = userInfo

      if (!mail) return message = t('请输入电子邮箱')
      if (!/\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/.test(mail)) return message = t('邮箱格式错误')
      if (!facebook) return message = t('请输入facebook链接')
      if (!maritalSheet.maritalKey) return message = t('请选择婚姻状况')
      if (!ducationSheet.ducationKey) return message = t('请选择学历')
      if (!industry) return message = t('请选择行业类型')
      if (!payday) return message = t('请选择发薪日')
      if (!monthlyIncome) return message = t('请输入每月净收入')

      if (!contactsInfo.mobile) return message = t('请选择') + t('联系人1')
      if (!contactsInfo.mobile_spare) return message = t('请选择') + t('联系人2')
      if (!contactsInfo.contactscolThreePhone) return message = t('请选择') + t('联系人3')
      if (!contactsInfo.contactscolFourPhone) return message = t('请选择') + t('联系人4')

      if (!positive) return message = t('请上传身份证正面')
      if (!livingImageUrl && switchConfig.isLivingSwitch) return message = t('请进行活体检测')
      if (!idCard) return message = t('身份证号码为空')
      if (!(fatherSurname && motherSurname && secondName)) return message = t('姓名为空')
      if (!gender) return message = t('请选择性别')
      if (!dateBirth) return message = t('请选择生日')
      return message
    }

    const confirm = debounce(
        async () => {
          if (!verificationInfo()) {
            const {mail, facebook, payday, monthlyIncome, industry} = userContact
            const userParams = {
              mail, facebook,
              maritalStatus: maritalSheet.maritalKey,
              degree: ducationSheet.ducationKey,
              liveDetailedAddress: 'abc',
            }
            const workParams = {
              industry,
              payday,
              monthlyIncome
            }
            const contactsParams = {
              ...contactsInfo,
              mobile: contactsInfo.mobile.toString().replace(/[^0-9]/ig, ""),
              mobile_spare: contactsInfo.mobile_spare.toString().replace(/[^0-9]/ig, ""),
              contactscolThreePhone: contactsInfo.contactscolThreePhone.toString().replace(/[^0-9]/ig, ""),
              contactscolFourPhone: contactsInfo.contactscolFourPhone.toString().replace(/[^0-9]/ig, ""),
            }
            const userInfoParams = {
              ...userInfo,
              name: (userInfo.fatherSurname + '-' + userInfo.motherSurname + '-' + userInfo.secondName).trim(),
              gender: userInfo.gender === t('男') ? 1 : 0,
              typeOfCertificate: idCardTypeColumns.value.find(v => userInfo.typeOfCertificate === v.value).key,
            }
            Toast.loading({
              message: t('加载中'),
              forbidClick: true,
              duration: 0,
            })
            const p1 = savePersonalInfo(userParams)
            const p2 = saveWorkInfo(workParams)
            const p3 = saveContacts(contactsParams)
            const p4 = userInfoConfirm(userInfoParams)
            Promise.all([p1, p2, p3, p4]).then(res => {
              console.log(res)
              const isTrue = res.every(v => v.code === 1)
              if (isTrue) {
                Toast({
                  message: t('提交成功')
                })
                processNext('')
                upLoadAdjustPoint({eventName: 'qwz1wn'})
              }
            })
          } else {
            upLoadPoint({type: 11})
            Toast({
              message: verificationInfo()
            })
          }
        }
    )

    // 提交埋点数据
    function confirmPoint(detailType) {
      upLoadInputPoint({
        type: 1,
        detailType: detailType
      })
    }

    //获取所有下拉
    const getSelect = async () => {
      const res = await personalInfoSelect()
      allSelectData.value = res.data
      idCardTypeColumns.value = res.data.filter(item => item.type === 26).map(item => {
        item.name = item.value
        return item
      })
      selectDataOne.value = res.data.filter(item => item.type === 8)
      selectDataTwo.value = res.data.filter(item => item.type === 19)
      selectDataThree.value = res.data.filter(item => item.type === 10)
      selectDataFour.value = res.data.filter(item => item.type === 21)
      // 清除loading
      store.dispatch('changeLoading', false)
    }
    // 流程显示隐藏
    const getResourcesShow = async () => {
      resourcesShow.value = await setResourcesShow(2)
      // 清除loading
      store.dispatch('changeLoading', false)
    }

    function handleClickLeft() {
      upLoadPoint({type: 10})
      dialogRetentionShow.value = true
    }

    async function getSwitch() {
      const res = await getConfigSwitch({productName: productName})
      if (res.code === 1) {
        const {ocrSwitch, livingSwitch, faceSwitch} = res.data
        switchConfig.isLivingSwitch = livingSwitch === 1
        switchConfig.isOcrSwitch = ocrSwitch === 1
        switchConfig.isFaceSwitch = faceSwitch === 1
      }
    }

    function openAddressBook(key) {
      if (window.android) {
        window.android.openSystemContactsPicker(key, 'saveContactsValue')
      }
    }

    function setContactsValue(value) {
      const keys = JSON.parse(value)
      if (verifiestContactsPhone(keys)) {
        if (keys.index === 0) {
          contactsInfo.mobile = keys.phoneNumber
          contactsInfo.name = keys.displayName
          upLoadAdjustPoint({eventName: 'lu107h'})
        } else if (keys.index === 1) {
          contactsInfo.mobile_spare = keys.phoneNumber
          contactsInfo.name_spare = keys.displayName
          upLoadAdjustPoint({eventName: 'q1o94b'})
        } else if (keys.index === 2) {
          contactsInfo.contactscolThreePhone = keys.phoneNumber
          contactsInfo.contactscolThreeName = keys.displayName
          upLoadAdjustPoint({eventName: 'n97r4p'})
        } else if (keys.index === 3) {
          contactsInfo.contactscolFourPhone = keys.phoneNumber
          contactsInfo.contactscolFourName = keys.displayName
          upLoadAdjustPoint({eventName: 'smqd2q'})
        }
      }
    }

    function verifiestContactsPhone(keys) {
      const {mobile, mobile_spare, contactscolThreePhone, contactscolFourPhone} = contactsInfo
      if ([mobile, mobile_spare, contactscolThreePhone, contactscolFourPhone].includes(keys.phoneNumber)) {
        Toast('The contact number cannot be selected repeatedly')
        return false
      }
      return true
    }

    function replaceAfter(str, char, replacement) {
      const regex = new RegExp(char + '.*');
      return str.replace(regex, replacement);
    }

    function changeEmailValue(value) {
      // if (value) {
      //   showEmailList.value = true
      // } else {
      //   showEmailList.value = false
      // }
      const strArr = emailStr.map(v => {
        if (value.indexOf('@') !== -1) {
          return {
            text: replaceAfter(value, '@', '@' + v)
          }
        } else {
          return {
            text: value + '@' + v
          }
        }
      })
      emailList.value = filterStr(strArr, value)
    }

    function filterStr(arr, str) {
      const hostStr = str.split('@')
      if (hostStr.length > 1) {
        const searchReg = new RegExp(hostStr[1], 'i')
        const sortArr = arr.sort((a, b) => {
          const aStr = searchReg.test(a.text)
          const bStr = searchReg.test(b.text)
          return !aStr && bStr ? 1 : aStr && !bStr ? -1 : 0
        })
        return sortArr
      }
      return arr
    }

    function onChangeEmailValue(value) {
      userContact.mail = value.text
    }

    function inputEventPoint(key) {
      upLoadAdjustPoint({eventName: key})
    }

    onMounted(() => {
      getSwitch()
      getResourcesShow()
      getSelect()
      setTimeout(() => {
        if (window.android) {
          window.android.checkPermission()
        }
      }, 5000)
      window.saveContactsValue = function (key) {
        console.log('saveContactsValue', key)
        setContactsValue(key)
      }
      upLoadAdjustPoint({eventName: 'uocgmh'})
    })
    return {
      ...toRefs(userContact),
      ...toRefs(maritalSheet),
      ...toRefs(ducationSheet),
      ...toRefs(contactsInfo),
      ...toRefs(userInfo),
      ...toRefs(sexSheet),
      ...toRefs(birthdaySheet),
      ...toRefs(industryTypeSheet),
      ...toRefs(relationSheet),
      ...toRefs(relationsSpareSheet),
      ...toRefs(relationsThreeSheet),
      ...toRefs(relationsTwoSheet),
      inputEventPoint,
      contactsInfo,
      switchConfig,
      selectDataOne,
      selectDataTwo,
      selectDataThree,
      selectDataFour,
      idCardTypeColumns,
      idCardTypeShow,
      idCardTypeConfirm,
      idCardPositiveShow,
      idCardTypeConfirmShow,
      idCardTypeImagePerView,
      openAddressBook,
      dialogRetentionShow,
      isOcrIdentify,
      salaryDateShow,
      salaryDateConfirm,
      confirmPoint,
      handleClickLeft,
      currentDate,
      allSelectData,
      confirm,
      resourcesShow,
      salaryDateColumns,
      updatePositive,
      beforeRead,
      livingBodyDetection,
      showEmailList,
      changeEmailValue,
      onChangeEmailValue,
      emailList
    }
  },
}
</script>

<style scoped lang="less">
::v-deep .van-popover__wrapper {
  display: block !important;
}

.van-popover__content {
  width: 300px;
}

.personalInfo {
  overflow: auto;


  ::v-deep .van-cascader__header {
    display: none;
  }

  .address_header {
    font-size: 16px;
    padding: 15px;
    box-sizing: border-box;
    background-color: #FFFFFF;

    .operation {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 15px;

      .confirm_text {
        color: #09B592;
      }
    }

    .input {
      margin-top: 10px;
      width: 100%;

      input {
        box-sizing: border-box;
        width: 100%;
        height: 35px;
        border-radius: 3px;
        padding: 5px 10px;
        outline: none;
        border: solid 1px #09B592;
      }
    }
  }

  .wrapper {
    box-sizing: border-box;

    .personalInfo_box_card {
      border-radius: 10px;
      padding-bottom: 1px;

      .personalInfo_box_card_header {
        margin-bottom: 10px;

        .text_highlight {
          color: #15B3B2;
          font-size: 16px;
        }

      }

      .input_contacts {
        border-radius: 16px;

        .contactsInfo_name {
          padding: 10px;
          margin-top: -10px;
          border-radius: 10px;
          color: #666666;
          background-color: #FFFFFF
        }
      }

      .contacts_icon {
        height: 24px;
        width: 24px;
        margin-right: -15px;
      }

      .title_round {
        height: 30px;
        width: 30px;
      }
    }
  }

  .card_box {
    text-align: center;
    padding: 10px;
    box-sizing: border-box;
    border-radius: 10px;
    background-color: #FFFFFF;

    .text {
      position: absolute;
      bottom: 10%;
      left: 50%;
      transform: translateX(-50%);
      color: #15B3B2;
      width: 100%;
    }

    .idCard_img {
      height: 100%;
      width: 100%;
    }
  }

  .grid_layout {
    display: grid;
    grid-template-columns: 1fr 1fr;
  }


}

::v-deep .van-action-sheet__description {
  background-color: #FFFFFF;
  font-size: 20px;
  color: #333333;
}
</style>
